import {replaceByObj,isImg} from './xUtil.js'
import{findParentsCodeByRc,hiberarchyToTree} from './treeUtil.js'

const tmplBase = '<div data-key="cntr" class="{{class}}"></div>';
const tmplMenuUl = '<ul {{id}} class="{{ulClass}}">{{ulHtml}}</ul>';
const tmplMenuLi = '<li>{{item}}{{liHtml}}</li> ';

const tmplMenuItem =`
		            <a {{href}}> 
		                {{icon}} {{name}} {{badge}}
		            </a>
		            {{drop}}`;
const tmplMenuItemCntr = '<div class="{{active}}" {{dataKey}} {{dataCode}}>{{item}}</div>';
const tmplMenuTagItem ='{{icon}} {{name}}';
const tmplHref = ' href="{{link}}"';
const tmplDataKey = 'data-key={{dataKey}}';
const tmplMenuBadge ='<span  class="x-badge {{type}}"></span>';
const tmplImg ='<img src="{{icon}}"  {{dataKey}}   {{dataCode}} >';
const tmplIcon ='<i class="iconfont {{icon}}" {{dataKey}} {{dataCode}} ></i>';

const dropDownIcon = 'icon-caret-right';


export default class xLeftMenu {
	// 定义变量
	$root;
	$container;
	//所以的上级 包括自己;
	vActiveCode = [];
	vJd = null;
	vIcon;

	constructor(cfg) {
		this.vJd = hiberarchyToTree(cfg.data);
		this.$root = $('#' + cfg.el);
		this.vIcon = cfg.icon?cfg.icon:dropDownIcon;
		this.$root.html(tmplBase.replace('{{class}}', !cfg.style ? 'menu-style-1' : cfg.style));
		this.$container = this.$root.find('[data-key="cntr"]');
		this.setAllActive(cfg.active);
		this.renderMenu();
		//事件
		this.$container.on('click', '[data-key="menu-drop"]', this.evClickNode.bind(this));

	}

	setAllActive(code) {
		let p = findParentsCodeByRc(this.vJd,code);
		p.reverse();
		this.vActiveCode = [...p];
		this.vActiveCode.push(code);
	}

	renderLi(item) {
		let html='';
		if(item.type && item.type=="tag")
		    html = this.renderMenuTagItem(item)
		else
			html = this.renderMenuItem(item,this.vActiveCode);
		return tmplMenuLi.replace('{{item}}',html);
	}

    renderMenuTagItem(jData){
        let icon = '';
        if(jData.icon){
            icon = isImg(jData.icon)?tmplImg:tmplIcon;
            icon = replaceByObj(icon, {dataKey:'',dataCode:'',icon:jData.icon});
        }

        let name = tmplName.replace('{{name}}', jData.name);
        let dataKey = tmplDataKey.replace('{{dataKey}}','menu-tag');
        let item = replaceByObj(tmplMenuTagItem,
            {name,icon});
        return  replaceByObj(tmplMenuItemCntr,{item,dataCode:'',dataKey,active:''});
    }

    renderMenuItem(jData,activeArray){
        let [badge,active,drop] = ['','',''];
        let href = jData.link;

        let icon = '';
        if(jData.icon){
            icon = isImg(jData.icon)?tmplImg:tmplIcon;
            icon = replaceByObj(icon, {dataKey:'data-key="menu-icon"',dataCode:'',icon:jData.icon});
        }

        if(jData.badge)
            badge = replaceByObj(tmplMenuBadge,
                {  type:jData.badge} );
        let name = tmplName.replace('{{name}}', jData.name);

        if(activeArray[activeArray.length-1] == jData.code){
            href =  '#';
            active = "active";
        }

        href = tmplHref.replace('{{link}}',href?href:'#');

        if(jData.children){
            drop = isImg(this.vIcon)?tmplImg:tmplIcon;
            drop = replaceByObj(drop, {dataKey:'data-key="menu-drop"',
                      dataCode:'data-code="'+jData.code+'"',icon:this.vIcon});
        }

        let dataKey = tmplDataKey.replace('{{dataKey}}','menu-item');
        if(jData.children)
            dataKey = tmplDataKey.replace('{{dataKey}}','menu-path');
        let item = replaceByObj(tmplMenuItem,
            {name,badge,icon,drop,href});

        return  replaceByObj(tmplMenuItemCntr,{item,dataCode:'',dataKey,active});

    }

	renderMenu() {
		let _this = this;
		function renderUl(items,parent) {
			let ulHtml = '';
			for(let o of items) {
				let liHtml = _this.renderLi(o);
				if(o.children) {
					liHtml = liHtml.replace('{{liHtml}}', renderUl(o.children,o));
				}else 
				    liHtml = liHtml.replace('{{liHtml}}','');
				ulHtml += liHtml;
			}
			let [id,ulClass] = ['',''];
			if(parent){
			    id = 'id="menu-code-'+parent.code+'"';
                ulClass =_this.vActiveCode.includes(parent.code)?'x-collapse x-in':'x-collapse';
            }
			return replaceByObj(tmplMenuUl,{id,ulClass,ulHtml});
		}
		this.$container.html(renderUl(this.vJd,1));
	}

	evClickNode(e) {
		let code = e.currentTarget.getAttribute("data-code");
		let $i = $(e.currentTarget);
		let $ul = $('#menu-code-' + code);
		if($ul.hasClass("x-in")) {
			$i.addClass("x-rotate-up");
			$i.removeClass("x-rotate-down");
			$ul.removeClass("x-in");
		} else {
			$i.addClass("x-rotate-down");
			$i.removeClass("x-rotate-up");
			$ul.addClass("x-in");
		}
	};

	setStyle(style){
		this.$container.attr("class",style);
	}

	refresh(){
		this.renderMenu();
	}

}